package cc.zy.base.hr.controller;

import cc.zy.base.businesses.entity.ErrorLog;
import cc.zy.base.businesses.mapper.EntranceScoreMapper;
import cc.zy.base.common.controller.BaseController;
import cc.zy.base.common.entity.FebsConstant;
import cc.zy.base.common.entity.QueryRequest;
import cc.zy.base.common.utils.FebsUtil;
import cc.zy.base.hr.entity.Emolument;
import cc.zy.base.common.annotation.ControllerEndpoint;
import cc.zy.base.common.entity.FebsResponse;
import cc.zy.base.common.exception.FebsException;
import cc.zy.base.hr.service.IEmolumentService;
import cc.zy.base.hr.util.ExcelUtil;
import cc.zy.base.hr.util.HrFileUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 薪酬及工资单数字助理
 *
 * @author LiuZhuang
 * @date 2022/03/08 17:57:38
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class EmolumentController extends BaseController {
    private final EntranceScoreMapper entranceScoreMapper;

    private final IEmolumentService emolumentService;

    /**
     * 导入薪资总表Excel数据，生成不同银行表格存在服务器端
     */
    @PostMapping("emolument/import")
    @ControllerEndpoint(exceptionMessage = "导入Excel数据失败")
    @ResponseBody
    public FebsResponse importEmolumentExcels(MultipartFile file, HttpServletRequest request) {

        log.debug(String.format("传入的文件流 file = %s", file));
        log.debug(String.format("失败日志的唯一标识 unique = %s",request.getSession().getAttribute("unique")));

        if (file.isEmpty()) {
            throw new FebsException("导入数据为空");
        }
        String filename = file.getOriginalFilename();
        if (!StringUtils.endsWith(filename, ".xlsx")) {
            log.error("只支持.xlsx类型文件导入");
            throw new FebsException("只支持.xlsx类型文件导入");
        }

        try {

            //读取文件并且数据判空，判空在工具类中封装到了errorLogs中，此处判断400直接参考案例写法返回
            FebsResponse febsResponse= ExcelUtil.readData(file);
            if(febsResponse.get("message").equals("400")){
                List<ErrorLog> errorLogs=(List<ErrorLog>)febsResponse.get("data");
//                获取错误行
                String unique = errorLogs.get(0).getUnique();
                request.getSession().setAttribute("unique", unique);
                entranceScoreMapper.addErrorLogList(errorLogs);
                return new FebsResponse().success().message("400");
            }
//            流程走到这里说明excel文件的主要数据没有问题，下面需要生成三张不同的表格和总表一并存储起来
//          获取总表信息等待生成分表
            List<Emolument> hrEmolumentExcels =(List<Emolument>)febsResponse.get("data");
            ApplicationHome applicationHome=new ApplicationHome(this.getClass());
            log.info(hrEmolumentExcels+"");
            //总表保存到服务器 返回总表文件名
            String TotalName=HrFileUtil.uploadTotal(file, applicationHome);
//            生成分表并且保存到服务器
            ExcelUtil.creatChongExcel(TotalName,hrEmolumentExcels,applicationHome);
            ExcelUtil.creatPoExcel(TotalName,hrEmolumentExcels,applicationHome);
            ExcelUtil.creatZhaoExcel(TotalName,hrEmolumentExcels,applicationHome);
            ExcelUtil.creatZhongExcel(TotalName,hrEmolumentExcels,applicationHome);
            log.info("上一行出了问题");
            return new FebsResponse().success().message("200");
        } catch (Exception e) {
            String code="500";
            log.error(e.toString());
            log.debug(String.format("返回的导入状态值 code = %s", code));
            return new FebsResponse().success().message(code);
        }

    }




    @GetMapping("emolument/list")
    @ResponseBody
    public FebsResponse emolumentList(QueryRequest request, Emolument emolument) {
        System.out.println("1111111");
        log.debug("前台传来的对象是：" + emolument);
        Map<String, Object> dataTable = getDataTable(emolumentService.findEmoluments(request, emolument));
        return new FebsResponse().success().data(dataTable);
    }




    @GetMapping("emolument/delete/{emolumentIds}")
    @ControllerEndpoint(operation = "删除院校", exceptionMessage = "删除院校异常")
    @ResponseBody
    public FebsResponse deleteEmoluments(@NotBlank(message = "{required}") @PathVariable String emolumentIds) {
        String[] ids = emolumentIds.split(StringPool.COMMA);
        emolumentService.deleteEmoluments(ids);
        return new FebsResponse().success();
    }

    @PostMapping("emolument/update")
    @ControllerEndpoint(operation = "修改院校", exceptionMessage = "修改院校信息异常")
    @ResponseBody
    public FebsResponse updateEmolument(@Valid Emolument emolument) {
        log.debug("修改院校id：" + emolument.getId());
        if (emolument.getId() == null) {
            throw new FebsException("院校ID为空");
        }

        return new FebsResponse().success();
    }


    /**
     * 方法描述：查找院校简称
     *
     * @param
     * @return cc.zy.base.common.entity.FebsResponse
     * @author houweikang
     * @date 2021/2/3
     */
    @GetMapping("emolument/findById/{emolumentId}")
    @ResponseBody
    public FebsResponse findById(@PathVariable Integer emolumentId) {

        log.debug(String.format("collegeId = %s", emolumentId));

        Emolument emolument = emolumentService.findById(emolumentId);
        return new FebsResponse().success().data(emolument);
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "emolument/add")
    public String emolumentAdd() {
        return FebsUtil.hrView("emolument/emolumentAdd");
    }

    private void resolveEmolumentModel(Integer id, Model model, Boolean transform) {

        Emolument emolument = emolumentService.findById(id);
        model.addAttribute("emolument", emolument);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "emolument/detail/{id}")
    public String emolumentDetail(@PathVariable Integer id, Model model) {

        resolveEmolumentModel(id, model, true);
        return FebsUtil.hrView("emolument/emolumentDetail");
    }
}
